import React, { useState, useEffect, useRef } from 'react';
import ATable from '@apulis/table';
import type { ATableColumn, SearchToolBarProps } from '@apulis/table';
import type { ActionType } from '@apulis/table/lib/typing';
import { Button, Card, message, Modal, Popover } from 'antd';
import { Link, useIntl } from 'umi';
import { listAPI, delEdgeNode, getCode } from './service';
import { edgeRequest } from '@/utils/request';
import trans from '@/utils/translate';
import { ExclamationCircleOutlined, InfoCircleFilled } from '@ant-design/icons';
import { getStatus } from './status';
import format from '@/utils/format';
import SyntaxCopy from '@/components/InfoShow/SyntaxCopy';

interface TableItemType {
  status: string;
  nodeId: string;
  nodeName: string;
};


const List: React.FC = () => {
  const { formatMessage: f } = useIntl();
  const tableRef = useRef<ActionType>();
  const handleDelete = (nodeId: string) => {
    Modal.confirm({
      centered: true,
      closable: true,
      icon: <ExclamationCircleOutlined />,
      maskClosable: true,
      okType: 'danger',
      okText: f({ id: 'operation.confirm' }),
      cancelText: f({ id: 'operation.cancel' }),
      width: '30%',
      title: <div style={{ fontWeight: 'bold' }}>
        {f({ id: 'operation.delete.confirm' })}
      </div>,
      content: <div>{f({ id: 'operation.delete.reconfirm' })}</div>,
      onOk: async () => {
        const res = await delEdgeNode(nodeId);
        if (res.code === 0) {
          message.success(f({ id: 'operation.delete.success' }));
          tableRef.current?.reload();
        }
      },
      cancelButtonProps: {},
      onCancel: () => {},
    });
  }
  const handleOffline = () => {
    getCode().then(res => {
      if (res && res.code === 0) {
        const code = res.data.data;
        Modal.info({
          centered: true,
          closable: true,
          icon: <ExclamationCircleOutlined style={{color: 'red'}}/>,
          maskClosable: true,
          width: '50%',
          title: (
          <div style={{ fontWeight: 'bold' }}>
            {f({ id: 'nodeManagement.edgeNode.offEdgeNode.title' })}
          </div>
          ),
          content: <div>
            <p>{f({ id: 'nodeManagement.edgeNode.offEdgeNode.stepOne' })}</p>
            <p>{f({ id: 'nodeManagement.edgeNode.offEdgeNode.stepTwo' })}</p>
            <p>{f({ id: 'nodeManagement.edgeNode.offEdgeNode.stepThree' })}</p>
            <SyntaxCopy code={code}></SyntaxCopy>
          </div>,
          onCancel: () => {},
        });
      }
    })
  }

  const columns: ATableColumn<TableItemType>[] = [
    {
      title: trans('nodeManagement.edgeNode.nodeName'),
      dataIndex: 'nodeName',
      render: (text, record) => (
        <Link to={`/node-management/edge-node/node-detail/${record.nodeId}`}>{text}</Link>
      )
    },
    {
      title: trans('nodeManagement.edgeNode.nodeType'),
      dataIndex: 'nodeType',
    },
    {
      title: trans('nodeManagement.edgeNode.status'),
      dataIndex: 'status',
      render: (text, record) => (
        <span>
          {getStatus(text)}
          { text === 'uninstall' &&
            <Popover content={trans('nodeManagement.edgeNode.checkScript')}>
              <Link
                style={{color: 'red', marginLeft: '5px'}}
                to={`/node-management/edge-node/add-node?down=true&id=${record.nodeId}&name=${record.nodeName}`}>
                <InfoCircleFilled />
              </Link>
            </Popover>
          }
        </span>
      )
    },
    {
      title: trans('nodeManagement.edgeNode.creator'),
      dataIndex: 'userName',
    },
    {
      title: trans('nodeManagement.edgeNode.createdAt'),
      dataIndex: 'createdAt',
      sortable: true,
      render: (text) => format(text),
    },
    {
      title: trans('operation'),
      render: (text, record) => record.status === 'online' ?
        <a onClick={() => handleOffline()} style={{ marginRight: 8, color: 'blue' }}>
          {trans('nodeManagement.edgeNode.Offline')}
        </a> :
        <a onClick={() => handleDelete(record.nodeId)} style={{ marginRight: 8, color: 'red' }}>
          {trans('common.delete')}
        </a>
    },
  ];
  const searchList: SearchToolBarProps[] = [
    {
      type: 'select',
      name: 'status',
      label: f({ id: 'info.status' }),
      selectOptions: [
        { label: f({ id: 'status.uninstall'}), value: 'uninstall' },
        { label: f({ id: 'status.online'}), value: 'online' },
        { label: f({ id: 'status.offline'}), value: 'offline' },
      ],
      placeholder: f({ id: 'info.status.select.please' }),
      selectProps: { allowClear: true }
    },
  ]


  return (
    <Card>
      <ATable
        actionRef={tableRef}
        request={edgeRequest}
        dataSourceAPIPath={listAPI}
        columns={columns}
        rowKey='id'
        searchToolBar={searchList}
        leftToolBar={(
          <Link to='/node-management/edge-node/add-node'>
            <Button type='primary'>{trans('menu.nodeManagement.addEdgeNode')}</Button>
          </Link>
        )}
      ></ATable>
    </Card>
  );
}

export default List;
